<template>
  <div class="common-wrapper">
    <a-card title="智能排班设置" :bordered="false">
      <a-form :form="form" :label-col="{ span: 2 }" :wrapper-col="{ span: 12 }" @submit="handleSubmit">
        <a-form-item label="默认班次">
          <a-select
            v-decorator="[
              'default_att_class',
              { rules: [{ required: true, message: '请选择默认班次' }], initialValue: formData.default_att_class },
            ]"
            placeholder="请选择默认班次"
            @change="handleSelectChange"
          >
            <a-select-option v-for="(item, index) of planList" :key="index" :value="index">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="排除班次">
          <a-select
            :filter-option="filterOption"
            mode="multiple"
            v-decorator="[
              'exclude_att_class',
              { rules: [{ required: true, message: '请选择排除班次' }], initialValue: formData.exclude_att_class },
            ]"
            placeholder="请选择排除班次"
            @change="handleSelectChange"
          >
            <a-select-option v-for="(item, index) of planList" :key="index" :value="index">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="最大偏移量">
          <a-input-number
            :min="Number(0)"
            :precision="Number(0)"
            placeholder="请输入最大偏移量"
            v-decorator="[
              'maximum_offset',
              { rules: [{ required: true, message: '请输入最大偏移量' }], initialValue: formData.maximum_offset },
            ]"
          />
        </a-form-item>
        <a-form-item label="部门设置">
          <a-table
            :columns="columns"
            :pagination="false"
            :data-source="tableData"
            size="small"
            bordered
            :scroll="{ y: 455 }"
            :rowKey="(record) => record.pkey"
          >
            <template slot="class" slot-scope="text, record">
              {{ setClassName(record.pkey) }}
            </template>
            <template slot="action" slot-scope="text, record">
              <a-button type="link" @click="openChangePlan(record)">修改班次</a-button>
            </template>
          </a-table>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 12, offset: 2 }">
          <a-button type="primary" html-type="submit"> 保存 </a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <a-modal :visible="visible" title="部门班次" @ok="setPlan" @cancel="handleCancelPlan">
      <a-select
        v-model="depInfo.class_list"
        :filter-option="filterOption"
        placeholder="请选择班次"
        mode="multiple"
        @change="handleSelectChange"
        labelInValue
        style="width: 400px"
      >
        <a-select-option v-for="(item, index) of planList" :key="index" :value="index">
          {{ item }}
        </a-select-option>
      </a-select>
    </a-modal>
  </div>
</template>
<script>
import pick from 'lodash.pick'
import difference from 'lodash/difference'
import { getAllDate } from '@/utils/util'
import { getConfig, setConfig, getClassSelect, getDepartmentList } from '@/api/plan'
export default {
  data () {
    return {
      form: this.$form.createForm(this),
      key: 'ATT_CLASS_CONFIG',
      planList: [],
      formData: {
        maximum_offset: 1,
        default_att_class: undefined,
        exclude_att_class: [],
        department_match: []
      },
      columns: [
        {
          dataIndex: 'dep_name',
          align: 'center',
          title: '部门',
          width: 180
        },
        {
          title: '部门班次',
          align: 'center',
          scopedSlots: { customRender: 'class' }
        },
        {
          title: '操作',
          align: 'center',
          width: 120,
          scopedSlots: { customRender: 'action' }
        }
      ],
      tableData: [],
      visible: false,
      depInfo: {
        dep_key: '',
        dep_name: '',
        class_list: []
      }
    }
  },
  async created () {
    await this.getPlanList()
    this.getDetail()
  },
  computed: {
    setClassName () {
      return (pkey) => {
        var text = ''

        const data = this.formData.department_match.find((item) => item.dep_key === pkey)
        if (data) {
          text = data.class_list.map((d) => d.class_name).toString()
        }
        return text
      }
    }
  },
  methods: {
    filterOption (input, option) {
      return option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
    },
    // setClassName (pkey) {
    //   var text = ''
    //   const data = this.formData.department_match.find((item) => item.p_key === pkey)
    //   if (data) {
    //     text = data.class_list.map((d) => d.class_name).toString()
    //   }
    //   return text
    // },
    handleCancelPlan () {
      this.visible = false
    },
    openChangePlan (record) {
      this.visible = true
      this.depInfo.dep_key = record.pkey
      this.depInfo.dep_name = record.dep_name
      const data = this.formData.department_match.find((item) => item.dep_key === record.pkey)
      if (data) {
        this.depInfo.class_list = data.class_list.map((d) => {
          return {
            key: d.class_key,
            label: d.class_name
          }
        })
      } else {
        this.depInfo.class_list = []
      }
    },
    setPlan () {
      this.visible = false
      const setData = {
        dep_key: this.depInfo.dep_key,
        dep_name: this.depInfo.dep_name,
        class_list: this.depInfo.class_list.map((i) => {
          return {
            class_key: i.key,
            class_name: i.label
          }
        })
      }
      const depInfo = this.formData.department_match.findIndex((item) => item.dep_key === this.depInfo.dep_key)
      if (depInfo > -1) {
        this.formData.department_match[depInfo] = setData
      } else {
        this.formData.department_match.push(setData)
      }
      // this.getDepartmentList()
    },
    // 获取部门列表
    async getDepartmentList () {
      const { data } = await getDepartmentList()
      this.tableData = data
    },
    handleSelectChange (value) {
      console.log(value)
    },
    // 获取班次下拉框
    async getPlanList () {
      await getClassSelect().then((res) => {
        if (res.statusCode === 200) {
          this.planList = res.data
        }
        return this.planList
      })
    },
    getDetail () {
      getConfig({
        key: this.key
      }).then((res) => {
        if (res.data) {
          res.data.default_att_class = res.data.default_att_class.toString()
          res.data.exclude_att_class = res.data.exclude_att_class.map(item => item.toString())
          this.formData = res.data
          this.formData.department_match = this.formData.department_match || []
          const {
            form: { setFieldsValue }
          } = this
          this.$nextTick(() => {
            setFieldsValue(pick(this.formData, ['default_att_class', 'exclude_att_class', 'maximum_offset']))
          })
        }
        this.getDepartmentList()
      })
    },
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          values.department_match = this.formData.department_match
          const data = {
            key: this.key,
            value: values,
            description: '智能排班配置'
          }
          setConfig(data).then((res) => {
            if (res.statusCode === 200) {
              this.$message.success('设置成功')
            } else {
              this.$message.error('设置失败')
            }
          })
        }
      })
    }
  }
}
</script>
<style scoped lang='less'>
.ant-input-number {
  width: 100%;
}
.common-wrapper {
  height: 100%;
  padding: 20px;
}
</style>
